/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
// 这种方式的最佳的解决方法就是使用层序遍历的方式来解决问题
var averageOfLevels = function (root) {
  if (root === null) {
    return [];
  }

  const result = [];
  const queue = [root];

  while (queue.length > 0) {
    const levelSize = queue.length;
    let sum = 0;

    for (let i = 0; i < levelSize; i++) {
      const current = queue.shift();
      sum += current.val;

      if (current.left !== null) {
        queue.push(current.left);
      }

      if (current.right !== null) {
        queue.push(current.right);
      }
    }

    // 计算当前层的平均值并加入结果数组
    result.push(sum / levelSize);
  }

  return result;
};